package com.zhanggm.springcloud.jpa.dao;

import com.zhanggm.springcloud.jpa.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

@Repository
public class UserDao {

    @Autowired
    private EntityManager entityManager;

    @Transactional
    public void save(UserEntity userEntity){
//        entityManager.persist(userEntity);
        entityManager.merge(userEntity);
    }

    public UserEntity getById(Integer id){
        UserEntity userEntity = entityManager.find(UserEntity.class, id);
        return userEntity;
    }

    @Transactional
    public UserEntity delById(Integer id){
        UserEntity byId = getById(id);
        entityManager.remove(byId);
        return byId;
    }

    public List<UserEntity> listLike(String username){
        Query query = entityManager.createQuery("from UserEntity u where u.username like :uname");
        query.setParameter("uname","%".concat(username).concat("%"));
        List resultList = query.getResultList();
        return resultList;
    }
}
